<template>
  <div class="blog-public-container">
    <div class="blog-header">
      <el-input v-model="blogTitle" placeholder="请输入文章标题" class="title-input" />
      <el-select v-model="selectedTags" placeholder="选择文章标签" class="tag-select">
        <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
      </el-select>
    </div>

    <div class="editor-container">
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
      <Editor style="height: 500px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
        @onCreated="handleCreated" />
    </div>

    <div class="blog-footer">
      <el-button type="primary" @click="publishBlog">发布文章</el-button>
      <el-button @click="saveDraft">保存草稿</el-button>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
import BlogHttp from '@/api/BlogHttp'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
const router  = useRouter()





const editorRef = shallowRef()
const valueHtml = ref('')
const blogTitle = ref('')
const selectedTags = ref([])
const tags = ref([])
const activeIndex = ref('0')

const handleSelect = (key) => {
    if (key === '0') {
        router.push({ name: 'home' })
    }
}
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: import.meta.env.VITE_BASE_URL + "upload",
      fieldName: 'image',
      compress: 0.5,
      uploadFileName: 'file',
      uploadImgMaxSize: 2 * 1024 * 1024,
      uploadImgMaxLength: 5,
      withCredentials: false,
      headers: {
        Authorization: `JWT ${authStore.token}`
      },
      // 自定义上传图片的回调
      customInsert(res, insertFn) {
        // 确保响应成功
        if (res.error === 0) {
          // 构建完整的图片URL
          const url = import.meta.env.VITE_BASE_URL + res.data.url
          // 插入图片，alt 和 href 可以根据需要传递
          insertFn(url)
          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error(res.msg || '图片上传失败')
        }
      },
      onError(file, err, res) {
        if (file.size > 2 * 1024 * 1024) {
          ElMessage.error("图片大小不能超过2M")
        } else {
          ElMessage.error("上传失败")
        }
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 草稿相关数据
const DRAFT_KEY = 'blog_draft'
const autoSaveInterval = ref(null)

// 只保留一个onMounted钩子
onMounted(async () => {
  try {
    // 获取博客分类
    let data = await BlogHttp.GetBlogCategory()
    tags.value = data

    console.log(localStorage.token)
    // 恢复草稿
    const savedDraft = localStorage.getItem(DRAFT_KEY)
    if (savedDraft) {
      const draft = JSON.parse(savedDraft)
      blogTitle.value = draft.title
      valueHtml.value = draft.content
      selectedTags.value = draft.tags
    } 

    // 设置自动保存（每30秒）
    autoSaveInterval.value = setInterval(() => {
      saveDraft(true)
    }, 30000)
  } catch (error) {
    ElMessage.error("获取博客分类失败")
  }
})

// 组件销毁时清除定时器
onBeforeUnmount(() => {
  if (autoSaveInterval.value) {
    clearInterval(autoSaveInterval.value)
  }
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 修改保存草稿方法，添加数据验证
const saveDraft = (isAuto = false) => {
  // 检查是否有内容需要保存
  if (!blogTitle.value && !valueHtml.value && selectedTags.value.length === 0) {
    return
  }

  const draft = {
    title: blogTitle.value,
    content: valueHtml.value,
    tags: selectedTags.value,
    lastSaved: new Date().toISOString()
  }

  try {
    localStorage.setItem(DRAFT_KEY, JSON.stringify(draft))
    if (!isAuto) {
      ElMessage.success('草稿已保存')
    }
  } catch (error) {
    ElMessage.error('草稿保存失败')
    console.error('保存草稿失败:', error)
  }
}

// 发布成功后清除草稿
const publishBlog = async () => {
  try {
    let title = blogTitle.value
    let content = valueHtml.value
    let category = selectedTags.value
    if (!title || !content || category.length === 0) {
      ElMessage.warning('请填写完整信息')
      return
    }
    const data = { title, content, category }
    await BlogHttp.SubmitBlog(data)
    ElMessage.success('发布成功')
    localStorage.removeItem(DRAFT_KEY)
    router.push({name:'home'})
  } catch (error) {
    console.error('发布失败:', error)
  }
}
</script>

<style scoped>
.blog-public-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.blog-header {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
}

.title-input {
  flex: 2;
}

.tag-select {
  flex: 1;
}

.editor-container {
  border: 1px solid #ccc;
  margin-bottom: 20px;
}

.blog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
